package com.wwd.movie.common.exception;

import com.wwd.movie.common.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 自定义业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public AjaxResult handleBusinessException(BusinessException ex) {
        return AjaxResult.error(ex.getCode(), ex.getMessage());
    }

    /**
     * 参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult handleValidationException(MethodArgumentNotValidException ex) {
        FieldError fieldError = ex.getBindingResult().getFieldError();
        String msg = fieldError != null ? fieldError.getDefaultMessage() : "参数校验失败";
        return AjaxResult.error(msg);
    }

    /**
     * 运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public AjaxResult handleRuntimeException(RuntimeException ex) {
        log.error("运行时异常：{}", ex.getMessage());
        return AjaxResult.error(ex.getMessage());
    }

    /**
     * 捕获所有异常
     */
    @ExceptionHandler(Exception.class)
    public AjaxResult handleException(Exception ex) {
        log.error("运行时异常：{}", ex.getMessage());
        return AjaxResult.error("系统异常：" + ex.getMessage());
    }
}
